<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/11/9  19:27
 */
namespace app\api\logic;
use app\api\BaseModel;
use think\Db;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as WXorder;
class Pay extends  BaseModel{

    /**
     * app
     */
    public function app()
    {
        $options = [
            'app_id' => config("wx.app_id"),

            'payment' => [
                'merchant_id'        =>config("wx.mch_id"),
                'key'                =>  config("wx.key"),
                'cert_path'          =>EXTEND_PATH. 'cert\apiclient_cert.pem', // XXX: 绝对路径！！！！
                'key_path'           => EXTEND_PATH.'cert\apiclient_key.pem',      // XXX: 绝对路径！！！！
                'notify_url'       => request()->domain().'/api/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            ],
        ];
        return  new Application($options);
    }
    /**
     * 收银台
     */
    public function cashier()
    {

        $db_order = db('order');
        $where['delete']=0;
        $where['id']=$this->requestData['id'];
        $where['uid']=$this->user['id'];
        $list=$db_order->where($where)->find();
        if(!$list) return array('message'=>'订单不存在');
        $list['countdown']=$list['create_time']+30*60-NOW_TIME;
        if( $list['countdown']<=0){
            $db_order->where($where)->update(array("status"=>-1));
            $list['status']=-1;
        }
        //if($list['status']==-1) return array('message'=>'订单已关闭，请重新下单');
        $list['num']=($list['end_time']-$list['start_time'])/(24*60*60);
        if($list['realname']){
            $list['realname']=unserialize($list['realname']);
        }
        $list['image']=IMG_PATH. $list['image'];

        $list['create_time']=date("Y-m-d H:i:s",$list['create_time']);
        $list['finish_time']=!empty($list['finish_time'])?date("Y-m-d H:i:s",$list['finish_time']):$list['finish_time'];
        $list['start_time']=date("Y-m-d",$list['start_time']);
        $list['end_time']=date("Y-m-d",$list['end_time']);
        $app=$this->app();
        $payment = $app->payment;

        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => '七彩虹酒店',
            'detail'           => $list['title'],
            'out_trade_no'     =>  $list['order_sn'],
            'total_fee'        => $list['price']*100, // 单位：分
            'notify_url'       => request()->domain().'/api/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->user['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];
        $order = new WXorder($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
            return array("detail"=>$list,'jsapi'=>$json);
        }elseif($result->return_code == 'FAIL'){
            return array("message"=>$result->return_msg);
        }
    }

    public function pay()
    {
        $app=$this->app();
        $payment = $app->payment;
        $db_order = db('order');
        $where['delete']=0;
        $where['id']=$this->requestData['id'];
        $list=$db_order->alias("o")
            ->field("m.openid,o.order_sn,o.title,o.price")
            ->join("member m","m.id=o.uid")
            ->where($where)->find();
        if(!$list) return array('message'=>'订单不存在');
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => '七彩虹酒店',
            'detail'           => $list['title'],
            'out_trade_no'     =>  $list['order_sn'],
            'total_fee'        => $list['price']*100, // 单位：分
            'notify_url'       => request()->domain().'/api/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $list['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];
        $order = new WXorder($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForJSSDKPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
            return array("detail"=>$list,'jsapi'=>$json);
        }elseif($result->return_code == 'FAIL'){
            return array("message"=>$result->return_msg);
        }
    }
    public function notify(){
        $xml = file_get_contents('php://input');
        if(!$xml){
            exit('非法访问');
        }
        $wx=$this->xmlToArray($xml);
        ksort($wx);// 对数据进行排序
        $str =$this-> ToUrlParams($wx);//对数据拼接成字符串
        $user_sign = strtoupper(md5($str));
        if($user_sign == $wx['sign']){//验证成功
            $log=db("order")->where("order_sn=".$wx['out_trade_no'])->find();

            if(!empty($log) && $log['status'] == '0' && (($wx['total_fee'] / 100) == $log['price'])) {//订单存在并且没支付状态，金额一致
                Db::startTrans();
                try{
                    $res=db("order")->where("order_sn=".$wx['out_trade_no'])->update(array("status"=>1,'pay_time'=>NOW_TIME));
                    $data=array(
                        'title'=>'订单号：'.$wx['out_trade_no'],
                        'image'=>$log['image'],
                        'des'=>'订单已支付，快去使用吧',
                        'uid'=>$log['uid'],
                        'create_time'=>NOW_TIME,
                        'relation_id'=>$log['id'],
                    );
                    $add=db("tip_user")->insert($data);
                    Db::commit();
                } catch (\Exception $e) {// 回滚事务
                    Db::rollback();
                    echo   $e->getMessage();
                    exit('fail');
                }
                if($log['cart_id'] || $log['code']){
                    (new Coupon())->deletecoupon($log['code'],$log['cart_id']);
                }
                if( $res) {
                    exit('success');
                }else{
                    exit('fail');
                }
            }
            exit('fail');
        }
        exit('fail');
    }
    public  function xmlToArray($xml)
    {

        //禁止引用外部xml实体

        libxml_disable_entity_loader(true);

        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

        $val = json_decode(json_encode($xmlstring), true);

        return $val;
    }
    /**
     * 格式化参数格式化成url参数
     */
    private function ToUrlParams($arr)
    {
        $weipay_key = config("wx.key");//微信的key,这个是微信支付给你的key，不要瞎填。
        $buff = "";
        foreach ($arr as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff.'&key='.$weipay_key;
    }

}